package com.gopay.common.cps.service.cbrmb;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.gopay.common.constants.autosettle.SettlementExchangeConstants;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.dic.GopayGlobalVariablesConstant;
import com.gopay.common.constants.trans.BCFlag;

import com.gopay.common.util.cbrmb.CbrmbJsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.gopay.common.cps.dao.autosettle.AsBankLimitConfigDAO;
import com.gopay.common.cps.dao.autosettle.AsCustLimitConfigDAO;
import com.gopay.common.cps.dao.autosettle.AsCustRuleDAO;
import com.gopay.common.cps.dao.global.GopayGlobalVariablesDao;
import com.gopay.common.domain.autosettle.AsBankLimitConfig;
import com.gopay.common.domain.autosettle.AsCustLimitConfig;
import com.gopay.common.domain.autosettle.AsCustRule;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.common.domain.cps.CpsGenPayOrder;
import com.gopay.common.order.dao.CommonQueryDAO;
import com.gopay.common.util.DateUtils;

/**
 * 跨境人民币自动结算辅助类
 * 
 * @CbRmbAutoSettleHelper.java
 * @author qianld
 * @2016年7月11日 下午5:38:16 www.gopay.com.cn Inc.All rights reserved.
 */
@Service(value = "cbRmbAutoSettleHelper")
public class CbRmbAutoSettleHelper {
	protected Logger logger = Logger.getLogger(getClass());
    @Resource(name = "commonQueryDAO")
    private CommonQueryDAO commonQueryDAO;

    @Resource(name = "asBankLimitConfigDAO")
    private AsBankLimitConfigDAO asBankLimitConfigDAO;

    @Resource(name = "asCustLimitConfigDAO")
    private AsCustLimitConfigDAO asCustLimitConfigDAO;
    
    
    @Resource(name = "asCustRuleDAO")
    private AsCustRuleDAO asCustRuleDAO;
    
    @Resource(name = "gopayGlobalVariablesDao")
    private GopayGlobalVariablesDao GopayGlobalVariablesDao;
    /**
     * 是否为节假日,holiday_type为02
     * @return
     */
    public boolean isHoliday(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        String year = DateUtils.format(calendar.getTime(), "yyyy");
        String month = DateUtils.format(calendar.getTime(), "M");
        String day = DateUtils.format(calendar.getTime(), "d");
        
        StringBuilder sb = new StringBuilder();
        
        sb.append(" select t.year, t.month, t.holidays ");
        sb.append("   from holiday_information t ");
        sb.append("  where 1 = 1       ");
        sb.append("    and ','||t.holidays||',' like :holidays ");
        sb.append("    and t.month=:month ");
        sb.append("    and t.year=:year ");
        sb.append("    and t.holiday_type = '02' ");

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("holidays", "%,"+day+",%");
        map.put("month", month);
        map.put("year", year);

        List<Object[]> rsList = commonQueryDAO.findBySql(sb.toString(), map);

        return rsList != null && rsList.size() > 0;
    }

    /**
     * 校验账户的工作日自动结算方案是否开通
     * 
     * @param acctId
     * @param intTxnCd
     * @param bankCode
     */
    public boolean isAcctWorkDayAutoSettleOpen(String acctId, String intTxnCd, String bankCode) {
        StringBuilder sb = new StringBuilder();

        sb.append(" select t.* ");
        sb.append("  from SS_TRANS_SETTLE_DTL t ");
        sb.append(" where t.bank_code = :bankCode ");
        sb.append("   and t.gopay_int_txn_cd = :intTxnCd ");
        sb.append("  and t.acct_id = :acctId ");

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("bankCode", bankCode);
        map.put("intTxnCd", intTxnCd);
        map.put("acctId", acctId);

        List<Object[]> rsList = commonQueryDAO.findBySql(sb.toString(), map);
        return rsList != null && rsList.size() > 0;
    }
    
    
    /**
     * 校验银行的自动结算是否开通
     * 
     * @param bankCode
     * @return
     */
    public boolean isBankAutoSettleOpen(String bankCode) {
        AsBankLimitConfig config = asBankLimitConfigDAO.findByBankCode(bankCode);

        return config != null && "1".equals(config.getSettleStatus());
    }

    /**
     * 校验银行自动结算限额是否允许本交易金额通过
     * 
     * @param bankCode
     * @param tranAmt
     * @return
     */
    public boolean isBankLimitAllow(String bankCode, BigDecimal tranAmt) {        
        AsBankLimitConfig config = asBankLimitConfigDAO.findByBankCode(bankCode);
        return tranAmt.add(config.getTodaySettleMoney()).compareTo(config.getLimitMoney()) <= 0;
    }

    /**
     * 校验客户T+0限额是否允许本交易金额通过
     * 
     * @param custId
     * @param tranAmt
     * @return
     */
    public boolean isCustT0LimitAllow(String custId, BigDecimal tranAmt,Date today) {
        // 统计00700,00800已用额度
        BigDecimal todayTotalMoney = new BigDecimal(0);
        StringBuilder sb = new StringBuilder();

        sb.append(" select m.pay_cust_id,sum(m.mer_txn_amt) ");
        sb.append(" from CPS_GEN_MAIN_ORDER m ");
        sb.append("  left join CPS_GEN_PAY_ORDER p on p.gopay_order_id = m.gopay_order_id ");
        sb.append(" where 1 = 1 ");
        sb.append("   and p.auto_settle ='1' ");
        sb.append("   and p.settlement_cycle=0 ");
        sb.append("   and (m.txn_sta_cd in(20000,30102) or p.PAY_STAT = '07')");
        sb.append("   and m.gopay_int_txn_cd in ('00700', '00800') ");
        sb.append("   and m.pay_cust_id=:custId ");
        sb.append("   and p.CUST_AUDIT_TIME>=to_timestamp(:today, 'yyyymmddHH24miss') ");
        sb.append("   group by m.pay_cust_id ");

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("today", DateUtils.format(today, "yyyyMMdd") + "000000");
        map.put("custId", custId);

        List<Object[]> rsList = commonQueryDAO.findBySql(sb.toString(), map);
        if (rsList != null && rsList.size() > 0) {
            todayTotalMoney = (BigDecimal) rsList.get(0)[1];
        }
        
        
        //统计01301已用额度
        sb = new StringBuilder();

        sb.append(" select m.mer_id,sum(m.mer_txn_amt) ");
        sb.append(" from CPS_GEN_MAIN_ORDER m ");
        sb.append("  left join CPS_GEN_PAY_ORDER p on p.gopay_order_id = m.gopay_order_id ");
        sb.append(" where 1 = 1 ");
        sb.append("   and p.auto_settle ='1' ");
        sb.append("   and p.settlement_cycle=0 ");
        sb.append("   and (m.txn_sta_cd in(20000,30101,30102) or p.PAY_STAT = '07')");
        sb.append("   and m.gopay_int_txn_cd ='01301' ");
        sb.append("   and m.mer_id=:custId ");
        sb.append("   and p.CUST_AUDIT_TIME>=to_timestamp(:today, 'yyyymmddHH24miss') ");
        sb.append("   group by m.mer_id ");
      
        rsList = commonQueryDAO.findBySql(sb.toString(), map);
        if (rsList != null && rsList.size() > 0) {
            BigDecimal tmpMoney = (BigDecimal) rsList.get(0)[1];
            todayTotalMoney=todayTotalMoney.add(tmpMoney);
        }

        // 查询客户T+0额度配置
        AsCustLimitConfig config = asCustLimitConfigDAO.findByCustId(custId);
        logger.info("商户T+0额度配置:"+ CbrmbJsonUtils.toJson(config));

        return tranAmt.add(todayTotalMoney).compareTo(config.getLimitMoney()) <= 0;
    }
    
    /**
     * 校验客户节假日白名单限额是否允许本交易金额通过
     * @param custId
     * @param ruleId
     * @param tranAmt
     * @return
     */
    public boolean isCustHolidayLimitAllow(String ruleId,BigDecimal tranAmt){
        //查询规则
        AsCustRule rule=asCustRuleDAO.find(AsCustRule.class, Long.valueOf(ruleId));
        if(rule==null||rule.isDel()){
            return false;
        }
        
        //统计该白名单规则的已用额度
        StringBuilder sb = new StringBuilder();
        
        sb.append(" select r.LIMIT_AMOUNT,sum(m.mer_txn_amt) ");
        sb.append(" from CPS_GEN_MAIN_ORDER m ");
        sb.append("  left join CPS_GEN_PAY_ORDER p on p.gopay_order_id = m.gopay_order_id ");
        sb.append("  left join AS_CUST_RULE r on r.RULE_ID = p.rule_id ");
        sb.append("  where 1 = 1 ");
        sb.append("  and r.IS_DEL ='0' ");
        sb.append("  and p.auto_settle ='1' ");
        sb.append("  and p.rule_id=:ruleId ");
        sb.append("  and (m.txn_sta_cd in(20000,30102) or p.PAY_STAT='07') ");
        sb.append("  and m.gopay_int_txn_cd in ('00700', '00800', '01301') ");
        sb.append("  and p.CUST_AUDIT_TIME>=to_timestamp(:startDay, 'yyyymmddHH24miss') ");
        sb.append("  group by r.LIMIT_AMOUNT ");
        
        //为了避免全表查询,只需要查询最近一个月的交易
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MONTH, -1);
        String startDay = DateUtils.format(calendar.getTime(), "yyyyMMdd");

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("startDay", startDay + "000000");
        map.put("ruleId", ruleId);

        List<Object[]> rsList = commonQueryDAO.findBySql(sb.toString(), map);
        BigDecimal ruleTotalMoney = new BigDecimal(0);
        if (rsList != null && rsList.size() > 0) {
            Object[] arr=rsList.get(0);
            ruleTotalMoney = (BigDecimal) arr[1];
        }
        
        
        
        return tranAmt.add(ruleTotalMoney).compareTo(rule.getLimitAmount()) <= 0;
      
    }
    
    /**
     * 校验收款人是否在某条节假日规则的白名单里
     * @param ruleId
     * @param intTxnCd
     * @param bankName
     * @param cardNo
     * @param holderName
     * @return
     */
    public boolean isRecvInHolidayRule(String ruleId,String intTxnCd,String cardNo,String holderName){
        StringBuilder sb = new StringBuilder();
        
        sb.append(" select l.rule_id,l.id ");
        sb.append("  from as_recv_info_list l ");
        sb.append("  left join as_cust_rule r on r.rule_id = l.rule_id ");
        sb.append(" where 1 = 1 ");
        sb.append("  and (l.recv_bank_acct_num is null or ");
        sb.append("      (l.recv_bank_acct_num = :cardNo and ");
        sb.append("      l.recv_bank_acct_name = :holderName)) ");
        sb.append("  and l.gopay_int_txn_cd = :intTxnCd ");
        sb.append(" and l.rule_id = :ruleId ");
        
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("holderName", holderName);
        map.put("cardNo", cardNo);
        map.put("intTxnCd", intTxnCd);
        map.put("ruleId", ruleId);

        List<Object[]> rsList = commonQueryDAO.findBySql(sb.toString(), map);
                
        return rsList != null && rsList.size() > 0;
    }
    
    /**
     * 根据银行名称查找银行Code
     * @param bankName
     * @return
     */
  /*  public String queryBankCodeByName(String bankName){
        String bankCode=null;
        
        StringBuilder sb = new StringBuilder();

        sb.append(" select t.bank_code,t.bank_name ");
        sb.append("  from bis_bank_info_main t ");
        sb.append(" where t.bank_name = :bankName ");

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("bankName", bankName);

        List<Object[]> rsList = commonQueryDAO.findBySql(sb.toString(), map);
        if(rsList != null && rsList.size() > 0){
            bankCode= (String)rsList.get(0)[0];
        }
        
        return bankCode;        
    }*/

    //需支持模糊匹配，后期需要维护银行别名
    public  String queryBankCodeByName(String bankName){
        if(bankName==null){
            return null;
        }
        
        if(bankName.indexOf("工行")!=-1 || bankName.indexOf("工商")!=-1){
            return BankConstants.BANK_LOGO_ICBC;
        }
        if(bankName.indexOf("招行")!=-1 || bankName.indexOf("招商")!=-1){
        	return BankConstants.BANK_LOGO_CMB;
        }
        if(bankName.indexOf("农行")!=-1 || bankName.indexOf("农业银行")!=-1){
        	return BankConstants.BANK_LOGO_ABC;
        }
        
        return null;
    }

	public Boolean isPettyAmt(BigDecimal merTxnAmt) {
		if (merTxnAmt.compareTo(new BigDecimal("50000.00")) == 1) {
			return false;
		}
		return true;
	}

	public Boolean isPrivate(String bcFlag) {
		// 是否对私
		if (StringUtils.equals(bcFlag, BCFlag.BC_FLAG_P.value)) {
			return true;
		}
		return false;
	}
	public Boolean isBankAcross() {
		String across = GopayGlobalVariablesDao.getGoPayGlobalVariablesByParamKey(GopayGlobalVariablesConstant.AS_BANK_ACROSS);
        if(StringUtils.isBlank(across)){
        	throw new RuntimeException("lack Global variables ");
        }
        logger.error("callBcdl globalVariables-----asBankAcross is "+across.toString());
        if(across.equalsIgnoreCase("1")){
        	return true;
        }
		return false;
	}
	public Object[] findCorrespondBank(String recvBankName,String recvBankNum) {
		Object[] r = findCorrespondBankByCardBin(recvBankName, recvBankNum);
		if(r!=null){
			logger.error("findCorrespondBankByCardBin:"+recvBankNum+" is "+r[0]);
			return r;
		}
		else{
			r= findCorrespondBankByrecvBankName(recvBankName, recvBankNum);
			if(r!=null) {
				logger.error("findCorrespondBank_ByrecvBankName:"+recvBankName+" is "+r[0]);
				return r;
			}
			else {
				logger.error("findCorrespondBank:null");
				return null;
			}
		}
	}
	public Object[] findCorrespondBankByCardBin(String recvBankName,String recvBankNum) {
		
		StringBuilder sb = new StringBuilder();
		sb.append("select c.pboc_bank_name,c.cnaps_code from ep_card_bin e ")
		.append(" left join DIC_PBOC_BANK_CONTRAST c on e.bank_fullname = c.alias_name ")
		.append(" where e.card_Front_No = SUBSTR(:cardNo, 0, e.card_Front_Length) ")
	    .append(" AND e.card_Length = LENGTH(:cardNo) AND c.enable = '1' ORDER BY e.card_Front_Length DESC");

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("cardNo",  recvBankNum);

        List<Object[]> rsList = commonQueryDAO.findBySql(sb.toString(), map);
        if(rsList != null && rsList.size() > 0){
            return rsList.get(0);
        }else{
            return null;
        }
	}
	public Object[] findCorrespondBankByrecvBankName(String recvBankName,String recvBankNum) {
		
		StringBuilder sb = new StringBuilder();
		sb.append("select c.pboc_bank_name,c.cnaps_code from DIC_PBOC_BANK_CONTRAST c ")
		.append(" where c.alias_name = :recvBankName AND c.enable = '1' ");
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("recvBankName",  recvBankName);
		
		List<Object[]> rsList = commonQueryDAO.findBySql(sb.toString(), map);
		if(rsList != null && rsList.size() > 0){
			return rsList.get(0);
		}else{
			return null;
		}
	}
	public Boolean existCorrespondBank(String recvBankName,String recvBankNum) {
		Object[] r = findCorrespondBank(recvBankName, recvBankNum);
		if(r!=null){
			return true;
		}
		else {
			return false;
		}
	}
    //需支持模糊匹配，后期需要维护银行别名
    public  String queryPayBankCode(CpsGenMainOrder mainOrder,CpsGenPayOrder payOrder){
    	String bankName = payOrder.getRecvBankName();
    	
    	if(bankName==null){
    		logger.error("gopayOrderId_" + mainOrder.getGopayOrderId()+" bankName is null");
    		return null;
    	}
    	
    	if(bankName.indexOf("工行")!=-1 || bankName.indexOf("工商")!=-1){
    		return BankConstants.BANK_LOGO_ICBC;
    	}
    	if(isBankAcross()){
	    	//对私小于等于5万走工行
	    	if(isPrivate(payOrder.getBcFlag())&&isPettyAmt(mainOrder.getMerTxnAmt())&&existCorrespondBank(payOrder.getRecvBankName(), payOrder.getRecvBankAcctNum())){
	    		logger.error("gopayOrderId_" + mainOrder.getGopayOrderId()+" bankName is ICBC(super)");
	    		return BankConstants.BANK_LOGO_ICBC;
	    	}
    	}
    	
    	if(bankName.indexOf("招行")!=-1 || bankName.indexOf("招商")!=-1){
    		return BankConstants.BANK_LOGO_CMB;
    	}
    	if(bankName.indexOf("农行")!=-1 || bankName.indexOf("农业银行")!=-1){
    		return BankConstants.BANK_LOGO_ABC;
    	}
    	
    	return null;
    }
    //需支持模糊匹配，后期需要维护银行别名
    public  String queryPayBankCode(CpsGenMainOrder mainOrder,String bankName,String bcFlag,String cardNum){
    	
    	if(bankName==null){
    		logger.error("gopayOrderId_" + mainOrder.getGopayOrderId()+" bankName is null");
    		return null;
    	}
    	if(bankName.indexOf("工行")!=-1 || bankName.indexOf("工商")!=-1){
    		return BankConstants.BANK_LOGO_ICBC;
    	}
    	if(isBankAcross()){
	    	//对私小于等于5万走工行
	    	if(isPrivate(bcFlag)&&isPettyAmt(mainOrder.getMerTxnAmt())&&existCorrespondBank(bankName, cardNum)){
	    		logger.error("gopayOrderId_" + mainOrder.getGopayOrderId()+" bankName is ICBC(super)");
	    		return BankConstants.BANK_LOGO_ICBC;
	    	}
    	}
    	
    	if(bankName.indexOf("招行")!=-1 || bankName.indexOf("招商")!=-1){
    		return BankConstants.BANK_LOGO_CMB;
    	}
    	if(bankName.indexOf("农行")!=-1 || bankName.indexOf("农业银行")!=-1){
    		return BankConstants.BANK_LOGO_ABC;
    	}
    	
    	return null;
    }
    //需支持模糊匹配，后期需要维护银行别名
    public  String selectSettlementExchange(CpsGenMainOrder mainOrder,CpsGenPayOrder payOrder){
    	String bankName = payOrder.getRecvBankName();
    	
    	if(bankName==null){
    		logger.error("gopayOrderId_" + mainOrder.getGopayOrderId()+" bankName is null");
    		return null;
    	}

    	if(bankName.indexOf("工行")!=-1 || bankName.indexOf("工商")!=-1){
    		return SettlementExchangeConstants.STLM_EX_ICBC;
    	}
    	if(isBankAcross()){
	    	//对私小于等于5万走工行超级网银
	    	if(isPrivate(payOrder.getBcFlag())&&isPettyAmt(mainOrder.getMerTxnAmt())&&existCorrespondBank(payOrder.getRecvBankName(), payOrder.getRecvBankAcctNum())){
	    		logger.error("gopayOrderId_" + mainOrder.getGopayOrderId()+" bankName is ICBC(super)");
	    		return SettlementExchangeConstants.STLM_EX_ICBC_SUPER;
	    	}
    	}
    	if(bankName.indexOf("招行")!=-1 || bankName.indexOf("招商")!=-1){
    		if (isPrivate(payOrder.getBcFlag())) {
    			return SettlementExchangeConstants.STLM_EX_CMB_P;
    		}
    		return SettlementExchangeConstants.STLM_EX_CMB_C;
    	}
    	if(bankName.indexOf("农行")!=-1 || bankName.indexOf("农业银行")!=-1){
    		return SettlementExchangeConstants.STLM_EX_ABC;
    	}
    	
    	return null;
    }

    /**
     * 查询节假日规则ID
     * @param custId
     * @param bankCode
     * @param curDate
     * @return
     */
    public String queryHolidayRuleId(String custId, String bankCode,Date curDate) {
        StringBuilder sb = new StringBuilder();

        sb.append(" select t.RULE_ID,t.CUST_ID ");
        sb.append("  from AS_CUST_RULE t ");
        sb.append(" where 1=1 ");
        sb.append("    and ','||t.PAY_BANK_CODES||',' like :bankCode ");
        sb.append("  and t.IS_DEL ='0' ");        
        sb.append("  and t.SETTLE_TIME_BEGIN<=to_timestamp(:curDate, 'yyyymmddHH24miss') ");
        sb.append("  and t.SETTLE_TIME_END>=to_timestamp(:curDate, 'yyyymmddHH24miss') ");
        sb.append("  and t.CUST_ID = :custId ");

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("bankCode",  "%,"+bankCode+",%");
        map.put("curDate", DateUtils.format(curDate, "yyyyMMddHHmmss"));
        map.put("custId", custId);

        List<Object[]> rsList = commonQueryDAO.findBySql(sb.toString(), map);
        if(rsList != null && rsList.size() > 0){
            return ((BigDecimal)rsList.get(0)[0]).toString();
        }else{
            return null;
        }
    }


    /**
     * 根据客户节假日白名单规则查询订单交易日期到今天的额外工作日
     * 
     * @param custId
     * @param cardNum
     * @param bankCode
     * @param tranDate
     * @param today
     * @return
     */
    public List<String> queryExtraWorkDayByCustHolidayRule(String custId, String cardNum, String bankCode,
            String tranDate, String today,String intTxnCd) {

        StringBuilder sb = new StringBuilder();

        sb.append(" select r.rule_id, ");
        sb.append("    r.settle_time_begin, ");
        sb.append("    r.settle_time_end, ");
        sb.append("    r.cust_id, ");
        sb.append("    d.recv_bank_acct_num, ");
        sb.append("    d.recv_bank_acct_name ");
        sb.append("  from AS_CUST_RULE r ");
        sb.append("  left join AS_RECV_INFO_LIST d on d.rule_id=r.rule_id ");
        sb.append(" where 1 = 1       ");
        sb.append(" and (d.recv_bank_acct_num = :cardNum or d.recv_bank_acct_num is null) ");
        sb.append("  and ','||r.PAY_BANK_CODES||',' like :bankCode ");
        sb.append("   and r.settle_time_end >= to_timestamp(:startDay, 'yyyymmddHH24miss') ");
        sb.append("   and r.settle_time_begin <= to_timestamp(:today, 'yyyymmddHH24miss') ");
        sb.append("  and r.IS_DEL ='0' ");
        sb.append("  and d.GOPAY_INT_TXN_CD=:intTxnCd ");
        sb.append("   and r.cust_id = :custId ");
        sb.append("  order by r.settle_time_begin asc ");

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("startDay", tranDate + "000000");
        map.put("today", today + "235959");
        map.put("custId", custId);
        map.put("cardNum", cardNum);
        map.put("bankCode",  "%,"+bankCode+",%");
        map.put("intTxnCd", intTxnCd);

        List<Object[]> rsList = commonQueryDAO.findBySql(sb.toString(), map);
        
        
        

        List<String> workList = new ArrayList<String>();
        if (rsList != null && rsList.size() > 0) {
            String ruleId,recvName;
            Date beginDate, endDate;
            for (Object[] arr : rsList) {
                ruleId=((BigDecimal)arr[0]).toString();
                beginDate = (Date) arr[1];
                endDate = (Date) arr[2];
                recvName = (String) arr[5];
                
                

                // 解析额外工作日列表
                workList.add(DateUtils.format(beginDate, "yyyyMMdd")+"#"+ruleId);
                
                String tmpEndDate = DateUtils.format(endDate, "yyyyMMdd");                
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(beginDate);
                for (int i = 0; i < 30; i++) {
                    calendar.add(Calendar.DAY_OF_MONTH, 1);                    
                    String tmpDay = DateUtils.format(calendar.getTime(), "yyyyMMdd");
                    if (tmpDay.compareTo(tmpEndDate) > 0) {
                        break;
                    }

                    workList.add(tmpDay+"#"+ruleId);
                }
            }
        }

        // 列表去重
        List<String> tempList = new ArrayList<String>();
        for (String i : workList) {
            if (!tempList.contains(i)) {
                tempList.add(i);
            }
        }
        return tempList;
    }

    /**
     * 查询最近一个月的法定工作日
     * 
     * @return
     */
    public List<String> queryLegalWorkDayOfRecentOneMonth(Date date) {

        // 本月
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        String y1 = DateUtils.format(calendar.getTime(), "yyyy");
        String m1 = DateUtils.format(calendar.getTime(), "M");
        String today = DateUtils.format(calendar.getTime(), "yyyyMMdd");

        // 上月
        calendar.add(Calendar.MONTH, -1);
        String y2 = DateUtils.format(calendar.getTime(), "yyyy");
        String m2 = DateUtils.format(calendar.getTime(), "M");
        String preMonth = DateUtils.format(calendar.getTime(), "yyyyMMdd");

        StringBuilder sb = new StringBuilder();

        sb.append(" select t.year, t.month, t.holidays ");
        sb.append("   from holiday_information t ");
        sb.append("  where 1 = 1       ");
        sb.append("    and ((t.year = :y1 and t.month = :m1) or ");
        sb.append("        (t.year = :y2 and t.month = :m2)) ");
        sb.append("    and t.holiday_type = '02' ");

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("y1", y1);
        map.put("m1", m1);
        map.put("y2", y2);
        map.put("m2", m2);

        List<Object[]> rsList = commonQueryDAO.findBySql(sb.toString(), map);

        // 获取节假日
        List<String> holidayList = new ArrayList<String>();
        if (rsList != null && rsList.size() > 0) {
            String holiday, month,prefix;
            for (Object[] arr : rsList) {
                prefix = (String) arr[0];

                month = (String) arr[1];
                if (month.length() == 1) {
                    prefix += "0";
                }
                prefix += month;
                                
                String[] dayArr = ((String) arr[2]).split(",");
                for (String day : dayArr) {
                    if (StringUtils.isNotBlank(day)) {
                        holiday=prefix;
                        if (day.length() == 1) {
                            holiday += "0";
                        }
                        holiday += day;
                        
                        holidayList.add(holiday);
                    }
                }
            }
        }

        // 计算工作日
        List<String> workList = new ArrayList<String>();

        calendar.setTime(date);
        for (int i = 0; i <= 31; i++) {
            if (i > 0) {
                calendar.add(Calendar.DAY_OF_MONTH, -1);
            }

            String tmpDay = DateUtils.format(calendar.getTime(), "yyyyMMdd");
            if (!holidayList.contains(tmpDay)) {
                workList.add(tmpDay);
            }
        }

        return workList;
    }
    
    
   
}
